import "./public-path";
import { createApp, App as AppInstance } from "vue";
import {
  createRouter,
  RouterHistory,
  Router,
  createWebHistory,
  createWebHashHistory,
} from "vue-router";
import App from "./App.vue";
import routes from "./router";
import Antd from "ant-design-vue";
import "ant-design-vue/dist/reset.css";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
dayjs.locale("zh-cn");

import { setCacheData } from "./utils/authority";
import { ConfigProvider } from "ant-design-vue";
declare global {
  interface Window {
    eventCenterForAppNameVite: any;
    __MICRO_APP_NAME__: string;
    __MICRO_APP_ENVIRONMENT__: string;
    __MICRO_APP_BASE_APPLICATION__: string;
    __MICRO_APP_BASE_ROUTE__: string;
  }
}

// 与基座进行数据交互
function handleMicroData(router: Router) {
  // eventCenterForAppNameVite 是基座添加到window的数据通信对象
  if (window.eventCenterForAppNameVite) {
    // 主动获取基座下发的数据
    console.log(
      "子应用收到的数据：",
      window.eventCenterForAppNameVite.getData()
    );
    const baseData = window.eventCenterForAppNameVite.getData();
    /** 基座数据存入缓存 */
    if (baseData) {
      const { token, sysAllDictItems, userInfo } = baseData || {};
      setCacheData(JSON.stringify({ sysAllDictItems, token, userInfo }));
    }

    // 监听基座下发的数据变化
    window.eventCenterForAppNameVite.addDataListener(
      (data: Record<string, unknown>) => {
        console.log("子应用收到的数据：", data);
        if (data.path && typeof data.path === "string") {
          data.path = data.path.replace(/^#/, "");
          // 当基座下发path时进行跳转
          if (data.path && data.path !== router.currentRoute.value.path) {
            router.push(data.path as string);
          }
        }
      }
    );

    // 向基座发送数据
    setTimeout(() => {
      window.eventCenterForAppNameVite.dispatch({
        myname: `${process.env.VUE_APP_CHILD_NAME}`,
      });
    }, 3000);
  }
}

// ----------分割线---umd模式------两种模式任选其一-------------- //
let app: AppInstance | null = null;
let router: Router | null = null;
let history: RouterHistory | null = null;
// 将渲染操作放入 mount 函数
function mount() {
  //hash模式 - 打包后可直接部署，无需服务器配置
  history = createWebHashHistory(
    window.__MICRO_APP_BASE_ROUTE__ || process.env.VUE_APP_BASE_URL
  );
  //history模式 - 需要服务器支持，否则会出现404
  // history = createWebHistory(
  //   window.__MICRO_APP_BASE_ROUTE__ || process.env.VUE_APP_BASE_URL
  // );
  router = createRouter({
    history,
    routes,
  });
  app = createApp(App);
  app.use(router).use(Antd).use(ConfigProvider);
  // 获取挂载点ID，如果环境变量未设置则使用默认值 'task'
  const mountId = process.env.VUE_APP_CHILD_NAME || 'task';
  // 确保 mountId 不为空，避免挂载点变成 '#'
  const selector = mountId ? `#${mountId}` : '#task';
  app.mount(selector);
  handleMicroData(router);
  // fixBugForVueRouter4(router);
}

// 将卸载操作放入 unmount 函数
function unmount() {
  app?.unmount();
  history?.destroy();
  // 卸载所有数据监听函数
  window.eventCenterForAppNameVite?.clearDataListener();
  app = null;
  router = null;
  history = null;
}

// 微前端环境下，注册mount和unmount方法
if (window.__MICRO_APP_ENVIRONMENT__) {
  // 使用类型断言明确指定属性类型
  const childName = process.env.VUE_APP_CHILD_NAME || 'task';
  (window as { [key: string]: any })[
    `micro-app-${childName}`
  ] = { mount, unmount };
} else {
  // 非微前端环境直接渲染
  mount();
}
